
package com.jf.cloud.im.socket.app;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.api.auth.feign.TokenFeignClient;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.util.Json;
import com.jf.cloud.im.constants.Constant;
import com.jf.cloud.im.constants.MsgCode;
import com.jf.cloud.im.vo.MessageInfoVO;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zz
 */
@ServerEndpoint("/ua/im/websocket/online/{token}/{userId}")
@Component
public class UserOnlineWebSocketServer {

    /**
     * UUID为key
     */
    public static final ConcurrentHashMap<String, Session> USER_ONLINE_MAP = new ConcurrentHashMap<>(256);

    private static TokenFeignClient tokenFeignClient;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        tokenFeignClient = applicationContext.getBean(TokenFeignClient.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        token = Base64.decodeStr(token);
        ServerResponseEntity<UserInfoInTokenBO> userInfoInTokenVoServerResponseEntity = tokenFeignClient.checkToken(token);
        if (!userInfoInTokenVoServerResponseEntity.isSuccess()) {
            throw new LuckException(userInfoInTokenVoServerResponseEntity.getMsg());
        }
        UserInfoInTokenBO userInfoInToken = userInfoInTokenVoServerResponseEntity.getData();
        if (userInfoInToken == null) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取用户信息")));
            }
            return;
        }

        // 如果原来就有token
        Session oldSession = USER_ONLINE_MAP.get(Constant.ONLINE_USER_PREFIX + userInfoInToken.getUserId() + Constant.UNDERLINE + token);
        if (oldSession != null) {
            // 客户端收到301，关闭ws链接，弹出提示
            if (oldSession.isOpen()) {
                oldSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.LOGIN_IN_OTHER_PLACE, "账户已在别处登录，请刷新")));
                oldSession.close();
            }
        }

        USER_ONLINE_MAP.put(Constant.ONLINE_USER_PREFIX + userInfoInToken.getUserId() + Constant.UNDERLINE + token, session);
        RedisUtil.set(Constant.ONLINE_USER_PREFIX + userInfoInToken.getUserId() + Constant.UNDERLINE + token, "", 0);
        if (session.isOpen()) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("token") String token, @PathParam(value = "userId") Long userId) throws IOException {
        USER_ONLINE_MAP.remove(Constant.ONLINE_USER_PREFIX + userId + Constant.UNDERLINE + token);
        RedisUtil.del(Constant.ONLINE_USER_PREFIX + userId + Constant.UNDERLINE + token);
    }

    /**
     * 连接错误调用的方法
     */
    @OnError
    public void onError(Session session, @PathParam("token") String token, Throwable error, @PathParam(value = "userId") Long userId) throws IOException {
        USER_ONLINE_MAP.remove(Constant.ONLINE_USER_PREFIX + userId + Constant.UNDERLINE + token);
        RedisUtil.del(Constant.ONLINE_USER_PREFIX + userId + Constant.UNDERLINE + token);
    }

    /**
     * 收到客户端消息后调用的方法，该消息由用户发过来
     *
     * @param sourceMessage 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String sourceMessage, @PathParam("token") String token, Session session) throws IOException {
        token = Base64.decodeStr(token);
        ServerResponseEntity<UserInfoInTokenBO> userInfoInTokenVoServerResponseEntity = tokenFeignClient.checkToken(token);
        if (!userInfoInTokenVoServerResponseEntity.isSuccess()) {
            throw new LuckException(userInfoInTokenVoServerResponseEntity.getMsg());
        }
        UserInfoInTokenBO userInfoInToken = userInfoInTokenVoServerResponseEntity.getData();
        if (Objects.isNull(userInfoInToken)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取用户信息")));
            }
            return;
        }

        if (StrUtil.isBlank(sourceMessage)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "内容格式有误")));
            }
            return;
        }

        MessageInfoVO messageInfo = Json.parseObject(sourceMessage, MessageInfoVO.class);

        if (Objects.isNull(messageInfo)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "内容格式有误")));
            }
            return;
        }

        // 保持心跳
        if (StrUtil.equals(messageInfo.getContent(), Constant.HEART_BEAT)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HEART_BEAT, "保持心跳")));
            }
            return;
        }

    }

}
